package com.example.servlet;

import com.example.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.example.domain.User;
@WebServlet("/UserRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
    private final UserDao userDao = new UserDao();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        User user = new User();
        //获取所以的参数的名字和属性，组成键值对，再通过copyProperties存到user对象set方法中的属性
//        BeanUtils.copyProperties(user, request.getParameterMap());
        user.setUsername(request.getParameter("username1"));
        user.setPassword(request.getParameter("password1"));
        user.setEmail(request.getParameter("email"));
        if (userDao.checkUsername(user.getUsername())){
            request.setAttribute("msg","用户名已存在！");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
        if (userDao.checkEmail(user.getEmail())){
            request.setAttribute("msg","邮箱已存在！");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
        int affectedRows = userDao.addUser(user);
        if (affectedRows==0){
           request.setAttribute("msg","注册失败！");
           request.getRequestDispatcher("register.jsp").forward(request, response);
        }else {
            request.setAttribute("msg","注册成功！");
            request.getSession().setAttribute("user",user);
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
//        放报错
//        response.sendRedirect(request.getContextPath()+"/login.jsp");

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
